<template>
  <div
    class="video-play-ptz-container"
    :class="{ landscape: currentLandscapeVid }"
  >
    <!--    :style="
        activeView === 'two'
          ? { position: 'absolute' }
          : { position: 'relative' }
      " -->
    <div class="header">
      <span>视频预览</span>
      <div
        v-if="activeView === 'four'"
        class="imgBox"
        :class="{ active: activeView === 'four' }"
        @click="switchView('two')"
      >
      <span>  四画面  </span>
    <img src="@/assets/images/xgjd/four.svg" alt="四画面视图" />
      </div>
      <div
        v-if="activeView === 'two'"
        class="imgBox"
        :class="{ active: activeView === 'two' }"
        @click="switchView('four')"
      >
      <span> 二画面</span> <img src="@/assets/images/xgjd/one.svg" alt="二画面视图" />
      </div>
    </div>

    <div
      class="video-box"
      :class="{
        'active-view-one': activeView === 'two',
        'rotate-landscape': currentLandscapeVid,
      }"
      :style="{ height: videoBoxHeight, width: videoBoxWidth }"
    >
      <!-- 横屏状态展示 -->
      <div v-if="currentLandscapeVid" style="width: 100vh; height: 100vw">
        <videobf
          :vid="currentLandscapeVid"
          :isSelected="true"
          :isLandscape="isFullScreen"
          @toggleLandscape="handleChildLandscape"
          :ref="(el) => el && videoRefs.push(el)"
        ></videobf>
      </div>
      <!-- 四画面视图 -->
      <div
        v-if="activeView === 'four' && !currentLandscapeVid"
        class="four-view"
      >
        <div
          v-for="(item, index) in currentDeviceIds"
          :key="index"
          class="video-item"
          @click="handleVideoSelect(item)"
        >
          <videobf
            :vid="item"
            :isSelected="selectedVid === item"
            :isLandscape="videoLandscapeStates[item]"
            @toggleLandscape="handleChildLandscape"
            :ref="(el) => el && videoRefs.push(el)"
          ></videobf>
        </div>
      </div>

      <!-- 二画面视图 -->
      <div v-if="activeView === 'two' && !currentLandscapeVid" class="two-view">
        <div
          v-for="(item, index) in currentDeviceIds"
          :key="index"
          @click="handleVideoSelect(item)"
          class="video-item"
        >
          <videobf
            :vid="item"
            :isSelected="selectedVid === item"
            :isLandscape="videoLandscapeStates[item]"
            @toggleLandscape="handleChildLandscape"
            :ref="(el) => el && videoRefs.push(el)"
          ></videobf>
        </div>
      </div>
    </div>
    <!-- 左右切换按钮--只有非横屏且有多个页面时才显示 -->
    <div class="center-btn" v-if="!currentLandscapeVid && hasMultiplePages">
      <el-icon @click="prevPage">
        <ArrowLeftBold />
      </el-icon>
      <el-icon @click="nextPage">
        <ArrowRightBold />
      </el-icon>
    </div>
  </div>
</template>

<script setup>
import {
  onMounted,
  ref,
  watch,
  computed,
  nextTick,
  onBeforeUnmount,
} from "vue";
import videobf from "./video.vue";

import { useRoute, useRouter } from "vue-router";
import {
  handlecameracontrol,
  getwithdrawtransferinfo,
} from "@/api/videoplan.js";
import { ArrowLeftBold, ArrowRightBold } from "@element-plus/icons-vue";

const route = useRoute();
const router = useRouter();
let currentIndexCode = ref("");
const selectedVid = ref("");
const videoLandscapeStates = ref({}); // 存储每个视频的横屏状态
// 视频组件引用数组
const videoRefs = ref([]);
// 横屏状态，使用与第二个组件一致的命名
const isFullScreen = ref(true);
const currentLandscapeVid = ref(""); // 当前横屏的视频ID（空=无横屏）
// 控制栏显示状态
const showControls = ref(false);
// 自动隐藏定时器
const autoHideTimer = ref(null);

// 视图切换状态
const activeView = ref("four");
const videoBoxHeight = ref("50vh");
const videoBoxWidth = ref("100%");
const deviceIds = ref([]); // 所有设备ID数组
const currentPage = ref(1); // 当前页码

let id = ref("");

// 根据视图类型获取每页显示数量
const itemsPerPage = computed(() => {
  return activeView.value === "four" ? 4 : 2;
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(deviceIds.value.length / itemsPerPage.value);
});

// 判断是否有多个页面
const hasMultiplePages = computed(() => {
  return totalPages.value > 1;
});

// 判断是否是第一页
const isFirstPage = computed(() => {
  return currentPage.value === 1;
});

// 判断是否是最后一页
const isLastPage = computed(() => {
  return currentPage.value === totalPages.value;
});

// 获取当前页面显示的设备ID
const currentDeviceIds = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage.value;
  const endIndex = startIndex + itemsPerPage.value;
  return deviceIds.value.slice(startIndex, endIndex);
});

// 上一页
const prevPage = () => {
  if (!isFirstPage.value) {
    currentPage.value--;
    resetControlsTimer();
  }
};

// 下一页
const nextPage = () => {
  if (!isLastPage.value) {
    currentPage.value++;
    resetControlsTimer();
  }
};

// 重置控制栏定时器
const resetControlsTimer = () => {
  if (autoHideTimer.value) {
    clearTimeout(autoHideTimer.value);
  }
  showControls.value = true;
  autoHideTimer.value = setTimeout(() => {
    showControls.value = false;
  }, 3000);
};

// 处理视频点击选中
const handleVideoSelect = (vid) => {
  // 如果点击已选中的视频则取消选中，否则选中
  selectedVid.value = selectedVid.value === vid ? "" : vid;
  resetControlsTimer();
};
//横屏
const handleChildLandscape = (data) => {
  const { vid, isLandscape } = data;
  console.log("子组件传来的横屏状态", isLandscape);
  if (!isLandscape) {
    // 关闭横屏时强制恢复多画面模式
    currentLandscapeVid.value = "";
    videoLandscapeStates.value[vid] = false;
    isFullScreen.value = false; // 修改这里

    // 恢复原始视图尺寸
    videoBoxHeight.value =
      activeView.value === "two" ? getOneViewHeight() : "100vh";
    videoBoxWidth.value = "100%";

    nextTick(() => {
      videoRefs.value.forEach((ref) => ref?.resize());
    });
  } else {
    // 开启横屏时隐藏其他视频
    currentLandscapeVid.value = vid;
    videoLandscapeStates.value[vid] = true;
    isFullScreen.value = true;
    videoBoxHeight.value = "100vw";
    videoBoxWidth.value = "100vh";

    nextTick(() => {
      videoRefs.value[0]?.resize();
    });
  }
};

// 切换视图
const switchView = (view) => {
  // 切换视图前先取消所有横屏状态
  Object.keys(videoLandscapeStates.value).forEach((key) => {
    videoLandscapeStates.value[key] = false;
  });
  isFullScreen.value = false;
  currentLandscapeVid.value = ""; // 重置横屏ID
  activeView.value = view;
  // 切换视图时重置到第一页
  currentPage.value = 1;
  resetControlsTimer();
};

const isIpad = () => {
  const ua = navigator.userAgent.toLowerCase();
  return (
    /ipad/.test(ua) || (window.innerWidth >= 768 && window.innerWidth <= 1024)
  );
};

// 定义不同设备的单视频高度
const getOneViewHeight = () => {
  if (isIpad()) {
    const isLandscapeScreen = window.innerWidth > window.innerHeight;
    return isLandscapeScreen ? "70vh" : "40vh";
  } else {
    return "50vh";
  }
};
// 监听横屏状态变化
watch(currentLandscapeVid, (newVal) => {
  videoRefs.value = []; // 重置子组件引用数组

  // 横屏时（newVal有值），等待子组件重新渲染后触发resize
  if (newVal) {
    nextTick(() => {
      console.log("watch横屏状态", newVal);
      if (videoRefs.value.length > 0) {
        videoRefs.value[0].resize();
        console.log("watch横屏状态触发子组件resize");
      }
    });
  }
});
// 监听视图变化，调整高度
watch(
  activeView,
  (newVal) => {
    if (!isFullScreen.value) {
      if (newVal === "two") {
        videoBoxHeight.value = getOneViewHeight();
      } else {
        videoBoxHeight.value = "100vh";
      }
    }
  },
  { immediate: true }
);

// 监听设备ID变化，重置页码
watch(
  () => deviceIds.value.length,
  () => {
    currentPage.value = 1;
  }
);

const handleTouchEnd = (e) => {
  e.preventDefault();
  setTimeout(() => {
    handlecameracontrol({
      action: 1,
      cameraId: currentIndexCode.value,
      command: "LEFT",
    });
  }, 30);
};

onMounted(async () => {
  // 点击视频区域显示控制栏
  document.addEventListener("click", (e) => {
    if (isFullScreen.value) {
      resetControlsTimer();
    }
  });

  if (route.query.type == "gongge") {
    currentIndexCode.value = route.query.transId;
    document.documentElement.classList.remove("video-fullscreen");
  } else {
    currentIndexCode.value = route.query.indexCode;
    localStorage.setItem("transId", currentIndexCode.value);
  }

  // 获取设备ID数组
  const res = await getwithdrawtransferinfo({
    transId: currentIndexCode.value,
  });

  deviceIds.value = res.data?.deviceIds || [];
  id.value = deviceIds.value[0] || "";

  // 初始化每个视频的横屏状态为false
  deviceIds.value.forEach((id) => {
    videoLandscapeStates.value[id] = false;
  });

  // 根据设备数量初始化视图类型
  activeView.value = deviceIds.value.length >= 4 ? "four" : "two";

  // 初始化页码
  currentPage.value = 1;
  // 初始化高度
  videoBoxHeight.value =
    activeView.value === "two" ? getOneViewHeight() : "100vh";
});

// 清理定时器
onBeforeUnmount(() => {
  if (autoHideTimer.value) {
    clearTimeout(autoHideTimer.value);
  }
  document.removeEventListener("click", () => {});
});
</script>


<style lang="scss" scoped>
/* 样式部分保持不变 */
::v-deep {
  @media only screen and (min-width: 768px) and (max-width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (min-width: 768px) and (max-width: 1366px) and (min-device-pixel-ratio: 1.5) {
    .video-box {
      overflow-x: hidden;
      .video-item {
        height: 40vh !important;
      }
      &.active-view-one {
            padding-top: 0px !important;
        top: 25%;
      }
    }
  }

  @media only screen and (min-width: 1024px) and (max-width: 1366px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (min-width: 1024px) and (max-width: 1366px) and (orientation: landscape) and (min-device-pixel-ratio: 1.5) {
    .video-box {
      overflow-x: hidden;
      .video-item {
        height: 40vh !important;
      }
      &.active-view-one {
            padding-top: 0px !important;
        top: 25%;
      }
    }
  }

  @media only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (min-width: 768px) and (max-width: 1024px) and (orientation: portrait) and (min-device-pixel-ratio: 1.5) {
    .video-box {
      overflow-x: hidden;
      .video-item {
        height: 40vh !important;
      }
      &.active-view-one {
            padding-top: 0px !important;
        top: 25%;
      }
    }
  }
}
::v-deep .fullscreen-video {
  .fullscreen-item {
    width: 100%;
    height: 100%;
  }
}
.video-play-ptz-container {
  width: 100%;
  height: 100%;
  overflow-y: hidden;
  overflow-x: hidden;
  background: #2f2f2f;
  padding-top: 20px;
  position: relative;

  .header {
    position: fixed;
    width: 100%;
    height: 50px;
    background: #2f2f2f;
    line-height: 50px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 27rpx;
    color: #ffffff;
    font-style: normal;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000 !important;
    .left-icon {
      position: absolute;
      left: 2%;
      cursor: pointer;
      :deep(.el-icon) {
        font-size: 20px;
      }
    }

    .imgBox {
      display: flex;
        align-items: center;
      position: absolute;
      right: 0;
      cursor: pointer;
      margin-right: 10px;

      img {
        width: 50rpx;
        height: 50rpx;
        filter: none;
        transition: filter 0.3s ease;

        &:not(.active-img) {
          filter: brightness(0) saturate(100%) invert(53%) sepia(0%)
            saturate(0%) hue-rotate(205deg) brightness(91%) contrast(87%);
        }
      }

      &.active {
        img {
          filter: brightness(0) saturate(100%) invert(73%) sepia(63%)
            saturate(507%) hue-rotate(338deg) brightness(101%) contrast(104%);
        }
      }
    }
  }

  .video-box {
    flex: 1;
    width: 100%;
    overflow-y: auto;
    // overflow-x: hidden;
    position: relative;
    padding-top: 70px;
    // 四画面布局
    &.four-view {
      width: 100%;
      height: 100%;
      overflow-y: auto;
    }
    // 二画面布局
    &.two-view {
      width: 100%;
      height: 100%;
      overflow-y: auto;
    }

    .video-item {
      width: 100%;
      height: 25vh;
      background-color: #000;
      transition: all 0.3s ease;
    }

    &.active-view-one {
        padding-top: 0px !important;
      // display: flex;
      // align-items: center;
      top: 25%;
    }
  }

  .center-btn {
    width: 100%;
    z-index: 9999 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    justify-content: space-between;

    > .el-icon {
      width: 40px;
      height: 40px;
      margin: 0 10px;
      font-size: 24px;
      color: #fff;
      cursor: pointer;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;

      &:hover {
        background-color: rgba(0, 0, 0, 0.7);
      }

      &:active {
        background-color: rgba(0, 0, 0, 0.8);
        transform: scale(1.05);
      }

      &.disabled {
        color: #888;
        background-color: rgba(0, 0, 0, 0.3);
        cursor: not-allowed;

        &:hover,
        &:active {
          background-color: rgba(0, 0, 0, 0.3);
          transform: none;
        }
      }
    }
  }
}

::v-deep .video-play-ptz-container.landscape {
  padding-top: 0 !important;
  overflow: hidden !important;
}

// 2. 视频盒子横屏旋转：旋转90度+校准位置，固定定位撑满屏幕
::v-deep .video-box.rotate-landscape {
  position: fixed !important; // 脱离文档流，避免影响其他元素
  top: 0 !important;
  left: 0 !important;
  // 旋转90度 + 向上平移100%自身高度（校准旋转后的偏移）
  transform: rotate(90deg) translate(0, -100%);
  transform-origin: top left !important; // 旋转原点设为左上角，方便计算
  width: 100vh !important; // 确保宽度至少等于视口高度（避免留白）
  height: 100vw !important; // 确保高度至少等于视口宽度（避免留白）
  overflow: hidden !important;
  z-index: 1000 !important; // 提高层级，避免被其他元素遮挡
  margin-top: 0% !important;
}

// 3. 横屏时视频项撑满容器（避免变形）
::v-deep .video-box.rotate-landscape .video-item {
  width: 100% !important;
  height: 100% !important;
}
// 4. 横屏时子组件视频撑满（避免黑边）
::v-deep .video-box.rotate-landscape .video-item video {
  width: 100% !important;
  height: 100% !important;
  object-fit: cover !important; // 覆盖容器，保持比例不拉伸
}
</style>
